import React from "react";
import axios from "axios";
import "./App.css";


class App extends React.Component {
  state = {
    list: [],
    activeIndex: -1,
  };
  handleClick(i) {
    console.log(this)
    this.setState({
      activeIndex: i,
    });
  }
  handleClickDocuemnt(e) {
    console.log(this)
    const ul = this.ul.current;
    const tar = e.target;

    if (!ul.contains(tar)) {
      this.setState({
        activeIndex: -1,
      });
    }
  }
  constructor(props) {
    super(props);
    this.ul = React.createRef();
    // 绑定 this 指向
    // this.handleClickDocuemnt = this.handleClickDocuemnt.bind(this);
  }
  render() {
    const { list, activeIndex } = this.state;
    return (
      <div>
        <h2>css 实现</h2>
        <ul className="title-box">
          {list.map((v, i) => {
            return (
              <li key={i} className="title qwer">
                <span>{v.count > 999 ? "999+" : v.count}</span>
                <span>{v.title}</span>
                <ol className="content-box">
                  {v.children.map((v, i) => {
                    return (
                      <li className="content-item" key={i}>
                        <b>&gt;</b>
                        <span>{v.title}</span>
                      </li>
                    );
                  })}
                </ol>
              </li>
            );
          })}
        </ul>

        <h2 style={{ marginTop: 100 }}>js 实现</h2>
        <div className="title-box" ref={this.ul}>
          {list.map((v, i) => {
            return (
              <li key={i} className="title" onClick={() => this.handleClick(i)}>
                <span>{v.count > 999 ? "999+" : v.count}</span>
                <span>{v.title}</span>
                <ol
                  className="content-box"
                  style={{ display: i === activeIndex ? "block" : "none" }}
                >
                  {v.children.map((v, i) => {
                    return (
                      <li className="content-item" key={i}>
                        <b>&gt;</b>
                        <span>{v.title}</span>
                      </li>
                    );
                  })}
                </ol>
              </li>
            );
          })}
        </div>
      </div>
    );
  }
  componentDidMount() {
    // 发送请求
    axios.get("/api/list").then((resp) => {
      console.log(resp.data.data);
      // 存储数据
      // 修改数据 唯一  方法
      this.setState({
        list: resp.data.data,
      });
    });

    // 添加绑定页面事件
    document.addEventListener("click", (e) => this.handleClickDocuemnt(e));
  }
  componentWillUnmount() {
    // 销毁绑定页面事件
    document.removeEventListener("click", (e) => this.handleClickDocuemnt(e));
  }
}

export default App;
